package net.samsb.bootReceiver;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.util.Log;

import net.samsb.BaseApplication;
import net.samsb.activity.MainActivity;
import net.samsb.log.LogUtils;

public class BootBroadcastReceiver extends BroadcastReceiver {

    static final String action_boot = "android.intent.action.BOOT_COMPLETED";

    @Override
    public void onReceive(Context context, Intent intent) {

        ConnectivityManager connectivityManager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo networkInfo = connectivityManager.getNetworkInfo(ConnectivityManager.TYPE_MOBILE);
        NetworkInfo wifiinfo = connectivityManager.getNetworkInfo(ConnectivityManager.TYPE_WIFI);

        Log.e("charge start", "启动完成");

        if (intent.getAction().equals(action_boot)) {

            Intent mBootIntent = new Intent(context, MainActivity.class);
            // 下面这句话必须加上才能开机自动运行app的界面
            mBootIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            context.startActivity(mBootIntent);
        }

        if (!networkInfo.isConnected() && !wifiinfo.isConnected()) {

            if (!BaseApplication.isNotNetWork) { //只执行一次

                BaseApplication.isNotNetWork = true; //无网络

                //分隔错误重连
                if (!BaseApplication.isReconnect) {

                    if (BaseApplication.BaseWebSocket != null) {

                        BaseApplication.BaseReconnectionWSThread.interrupt();
                        BaseApplication.BaseReconnectionWSThread.isStop = true;

                        LogUtils.e("getWebSocketMessage", "断网_重连");

                        BaseApplication.isReconnect = true;

                        BaseApplication.BaseWebSocket.close(4444,null);

                        BaseApplication.BaseRequestInstance.getWebSocketRequest().getWebSocketMessage(null);
                    }
                }

                LogUtils.e("NETWORK_STATUS", "网络不可用");
            }

        } else {

            BaseApplication.isNotNetWork = false;

            if (wifiinfo.isConnected()) {
                LogUtils.e("NETWORK_STATUS", "wifi连接中");
            }

            if (networkInfo.isConnected()) {
                LogUtils.e("NETWORK_STATUS", "流量连接中");
            }
        }

    }
}
